//
//  TabSwitchViewController.swift
//  YoruNeko
//
//  Created by hgc on 2021/6/21.
//

import Foundation
import SwiftUI

class TabViewController: UIViewController{
    struct YRNKControllerStruct {
        var uuid:UUID



        var hostingControllerPointer:YRNKHostingControllerPointer
    }
    
    //保存rootview的子viewcontroller，展示时用addSubView，用于保存不同标签页
    var childViewControllerList: [YRNKControllerStruct] = []
    var currentVC: YRNKHostingControllerPointer?
    weak var parentVC: YoruNekoViewController?
    var modelData: TabItemsModelData?

    
    init(_parent: YoruNekoViewController) {
        self.parentVC = _parent
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("doesn't implement this init method")
    }

    func setModelData(modelData: TabItemsModelData){
        self.modelData = modelData
        
    }
    
    func setParentController(parentVC: YoruNekoViewController){
        self.parentVC = parentVC
    }
    
    func getCurrentViewCount()->Int{
        return childViewControllerList.count
    }
    
    override func viewDidLoad() {
        NSLog("%s viewDidLoad", "TabViewController")
        let _ = self.addIndexView()
        showChildView(currentVC!)
        
        //time tag
        end = Date.init()
        
        YRNKLog("elapsed time:", msg: end.distance(to: start).description)
    }
    
    func changeView(uuid: UUID){
        guard let childVC = childViewControllerList.first(where: {$0.uuid == uuid}) else {
            return
        }
        showChildView(childVC.hostingControllerPointer)
    }
    func changeCurrentUrl(url: String){
        if let hostingController = currentVC as? YRNKHostingController<IndexView> {
            let indexView = hostingController.swiftUIView
            indexView.loadURL(urlStr: url)
        }
//        let realVC = currentVC as! UIHostingController<IndexView>
//        realVC.rootView.loadURL(urlStr: url)
    }
    //返回还剩多少窗口
    func removeViewById(uuid: UUID)-> Int{
//        var index = childViewControllerList.index(forKey: uuid)
//        index = childViewControllerList.index(after: index!)
        if let index = childViewControllerList.firstIndex(where: {$0.uuid == uuid}) {
            let childVCPointer = childViewControllerList.remove(at: index).hostingControllerPointer
            removeChildView(childVCPointer.getViewController())
            if childVCPointer.getViewController() === currentVC?.getViewController() {
                var nextVC:YRNKHostingControllerPointer?
                if index-1>=0 {
                    nextVC = childViewControllerList[index-1].hostingControllerPointer
                }
                if index+1<=childViewControllerList.count{
                    currentVC = nextVC
                }
            }
        }
        return childViewControllerList.count
    }
    func removeAllView(){
        childViewControllerList.removeAll()
        modelData?.TabItemList.removeAll()
        currentVC = nil
    }
    func addIndexView()->UUID{
        print("add indexVIew")
        //修改ModelData
        let newItem : TabItem = TabItem(logo: Image(systemName: "house.fill"), title: "首页", url: "",image: Image("index"))
        modelData?.TabItemList.append(newItem)
        let view = IndexView(uuid: newItem.id, indexCallback: parentVC)
        let viewEnvObj = view.environmentObject(modelData!)
        let childVC = UIHostingController(rootView: viewEnvObj)
        let childYRNKHostingController = YRNKHostingController.init(rootView: view, vc: childVC)
        //childViewControllerList.updateValue(childYRNKHostingController, forKey: newItem.id)
        childViewControllerList.append(YRNKControllerStruct.init(uuid: newItem.id, hostingControllerPointer: childYRNKHostingController))
        showChildView(childYRNKHostingController)
        return newItem.id
    }
    //用于管理childView
    private func showChildView(_ childVCPointer: YRNKHostingControllerPointer){
        //currentVC?.dismiss(animated: true, completion: {})
        print("showChildView")
        let childVC = childVCPointer.getViewController()
        currentVC = childVCPointer
        childVC.view.frame = self.view.bounds
        self.addChild(childVC)
        view.addSubview(childVC.view)
        childVC.didMove(toParent: self)
        //currentChildViewController = child
        //UINavigationController
    }
    
    private func updateCurrentVC(){
        
    }

    private func removeChildView(_ childVC: UIViewController){
        childVC.willMove(toParent: nil)
        childVC.view.removeFromSuperview()
        childVC.removeFromParent()
        //currentChildViewController = childViewControllerList.last
    }

}

extension TabViewController{
    func addIndexView(toLoadWD loadWD:String)->UUID{
        print("add indexVIew")
        //修改ModelData
        let newItem : TabItem = TabItem(logo: Image(systemName: "house.fill"), title: "首页", url: "",image: Image("index"))
        modelData?.TabItemList.append(newItem)
        let view = IndexView(uuid: newItem.id, indexCallback: parentVC,wdToload: loadWD)
        let viewEnvObj = view.environmentObject(modelData!)
        let childVC = UIHostingController(rootView: viewEnvObj)
        let childYRNKHostingController = YRNKHostingController.init(rootView: view, vc: childVC)
        //childViewControllerList.updateValue(childYRNKHostingController, forKey: newItem.id)
        childViewControllerList.append(YRNKControllerStruct.init(uuid: newItem.id, hostingControllerPointer: childYRNKHostingController))
        showChildView(childYRNKHostingController)
        return newItem.id
    }
}
